package com.theydream.qeechain.main;

import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.maps.GeoPoint;
import com.theydream.qeechain.R;
import com.theydream.qeechain.collection.PetInfo;
import com.theydream.qeechain.facebook.FacebookConnector;
import com.theydream.qeechain.facebook.SessionEvents;
import com.theydream.qeechain.globaldata.CaughtItemListClass;
import com.theydream.qeechain.globaldata.GlobalData;
import com.theydream.qeechain.globaldata.definition.CaughtPet;

public class MyPet extends Activity {
	private static final String FACEBOOK_APPID = "183524461720661";
	private static final String FACEBOOK_PERMISSION = "publish_stream";
	private static final String TAG = "FacebookSample";
	private static final String MSG = "Message from FacebookSample";

	private final Handler mFacebookHandler = new Handler();
	private TextView loginStatus;
	private FacebookConnector facebookConnector;
	TextView petAddress;
	Location location;
	CaughtPet mPet;
	Address mAddress;
	final Runnable mUpdateFacebookNotification = new Runnable() {
		public void run() {
			Toast.makeText(getBaseContext(), "Facebook updated !",
					Toast.LENGTH_LONG).show();
		}
	};

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.pet_info);
		this.facebookConnector = new FacebookConnector(FACEBOOK_APPID, this,
				getApplicationContext(), new String[] { FACEBOOK_PERMISSION });

//		Bundle bundle = this.getIntent().getExtras();

		// ===========================================
		// | Get View By Id from xml
		// ===========================================
		RelativeLayout infoBg = (RelativeLayout) findViewById(R.id.pet_info_bg);
		ImageView petImage = (ImageView) findViewById(R.id.pet_image);
		ImageView facebook = (ImageView) findViewById(R.id.facebook);
		TextView petName = (TextView) findViewById(R.id.pet_name);
		TextView petDesc = (TextView) findViewById(R.id.pet_desc);
		TextView petTime = (TextView) findViewById(R.id.caught_time);
		TextView petS = (TextView) findViewById(R.id.strength);
		TextView petP = (TextView) findViewById(R.id.perception);
		TextView petE = (TextView) findViewById(R.id.endurance);
		TextView petC = (TextView) findViewById(R.id.charisma);
		TextView petI = (TextView) findViewById(R.id.intelligence);
		TextView petA = (TextView) findViewById(R.id.agility);
		TextView petL = (TextView) findViewById(R.id.luck);
		petAddress = (TextView) findViewById(R.id.caught_address);
		facebook.setClickable(true);
		facebook.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				postMessage();
			}

		});

		// ===========================================
		// | Bind infomation to view
		// ===========================================
//		if (bundle != null) {
		mPet = CaughtItemListClass.getInstance().getItemList()
				.get(GlobalData.getInstance().getDbhelper().getPetInUse());

		// get drawable resource by name
		petImage.setImageResource(getResources().getIdentifier(
				mPet.getPet().getPic(), "drawable", this.getPackageName()));
		petName.setText(mPet.getPet().getName());
		petTime.setText(mPet.getTime());
		petDesc.setText(mPet.getPet().getDesc());

		Map<String, Integer> map = mPet.getPet().getAttr();
		petS.setText(map.get("S").toString());
		petP.setText(map.get("P").toString());
		petE.setText(map.get("E").toString());
		petC.setText(map.get("C").toString());
		petI.setText(map.get("I").toString());
		petA.setText(map.get("A").toString());
		petL.setText(map.get("L").toString());

		LoadAddressTask task=new LoadAddressTask();
		task.execute(null);
	}

//	}

	public void postMessage() {

		if (facebookConnector.getFacebook().isSessionValid()) {
			postMessageInThread();
		} else {
			SessionEvents.AuthListener listener = new SessionEvents.AuthListener() {

				@Override
				public void onAuthSucceed() {
					postMessageInThread();
				}

				@Override
				public void onAuthFail(String error) {

				}
			};
			SessionEvents.addAuthListener(listener);
			facebookConnector.login();
		}
	}

	private void postMessageInThread() {
		Thread t = new Thread() {
			public void run() {

				try {
					facebookConnector.postMessageOnWall(getFacebookMsg());
					mFacebookHandler.post(mUpdateFacebookNotification);

				} catch (Exception ex) {
				}
			}
		};
		t.start();
	}

	private String getFacebookMsg() {
		return MSG + " at " + new Date().toLocaleString();
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		this.facebookConnector.getFacebook().authorizeCallback(requestCode,
				resultCode, data);
	}

	public void updateLoginStatus() {
		loginStatus.setText("Logged into Twitter : "
				+ facebookConnector.getFacebook().isSessionValid());
	}

	@Override
	protected void onResume() {
		super.onResume();
		
		// ===========================================
		// | Get View By Id from xml
		// ===========================================
		RelativeLayout infoBg = (RelativeLayout) findViewById(R.id.pet_info_bg);
		ImageView petImage = (ImageView) findViewById(R.id.pet_image);
		ImageView facebook = (ImageView) findViewById(R.id.facebook);
		TextView petName = (TextView) findViewById(R.id.pet_name);
		TextView petDesc = (TextView) findViewById(R.id.pet_desc);
		TextView petTime = (TextView) findViewById(R.id.caught_time);
		TextView petS = (TextView) findViewById(R.id.strength);
		TextView petP = (TextView) findViewById(R.id.perception);
		TextView petE = (TextView) findViewById(R.id.endurance);
		TextView petC = (TextView) findViewById(R.id.charisma);
		TextView petI = (TextView) findViewById(R.id.intelligence);
		TextView petA = (TextView) findViewById(R.id.agility);
		TextView petL = (TextView) findViewById(R.id.luck);
		petAddress = (TextView) findViewById(R.id.caught_address);
		facebook.setClickable(true);
		facebook.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				postMessage();
			}

		});

		// ===========================================
		// | Bind infomation to view
		// ===========================================
//		if (bundle != null) {
		mPet = CaughtItemListClass.getInstance().getItemList()
				.get(GlobalData.getInstance().getDbhelper().getPetInUse());

		// get drawable resource by name
		petImage.setImageResource(getResources().getIdentifier(
				mPet.getPet().getPic(), "drawable", this.getPackageName()));
		petName.setText(mPet.getPet().getName());
		petTime.setText(mPet.getTime());
		petDesc.setText(mPet.getPet().getDesc());

		Map<String, Integer> map = mPet.getPet().getAttr();
		petS.setText(map.get("S").toString());
		petP.setText(map.get("P").toString());
		petE.setText(map.get("E").toString());
		petC.setText(map.get("C").toString());
		petI.setText(map.get("I").toString());
		petA.setText(map.get("A").toString());
		petL.setText(map.get("L").toString());

		
	}

	public void goBack(View target) {
		this.finish();
	}
	public class LoadAddressTask extends AsyncTask <Void, Void, Void>{
		ProgressDialog dialog;
		View view;

		Context mContext;
		GlobalData globalData=GlobalData.getInstance();
		

		@Override
		protected void onPreExecute()
		{
			dialog=new ProgressDialog(MyPet.this);
			dialog.setMessage("Loading...");
			dialog.show();
		}
		@Override
		protected Void doInBackground(Void... params) {
			// ===========================================
			// | Location to Address
			// ===========================================
			location = new Location("Caught Location");
			location.setLatitude(Double.valueOf(mPet.getLat()));
			location.setLongitude(Double.valueOf(mPet.getLng()));
			double geoLatitude = location.getLatitude() * 1E6;
			double geoLongitude = location.getLongitude() * 1E6;
			GeoPoint gp = new GeoPoint((int) geoLatitude,
					(int) geoLongitude);

			Geocoder gc = new Geocoder(MyPet.this, Locale.CHINA);

			double Latitude = (int) gp.getLatitudeE6() / 1E6;
			double Longitude = (int) gp.getLongitudeE6() / 1E6;

			List<Address> lstAddress;
			try {
				lstAddress = gc.getFromLocation(Latitude, Longitude, 1);
				if (lstAddress.size() > 0) {
					mAddress = lstAddress.get(0);
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return null;
			
		}
		protected void onPostExecute(Void result)
		{
			dialog.dismiss();
			if (mAddress!=null)
			{
			petAddress.setText(mAddress.getAddressLine(1)
					.toString());
			}
		}
	}
//	}
		
		// updateLoginStatus();

}
